<template>
    <el-dialog title="装盒" :visible.sync="open" width="50%" append-to-body :before-close="closeDelDialog">
        <div class="boxMain">

            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="盒数：">
                    <el-input type="number" v-model="num" placeholder="请输入正整数"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onQuery">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="tableData" border style="width: 100%" header-align="center">
                <el-table-column prop="hehao" label="盒号" width="180" align="center">
                    <template slot-scope="scope" >
                        <el-input   v-if="scope.$index==0&&isAvailable.maxHehaoIsAvailable == 'yes'" type="text" v-model="scope.row.hehao" @change="onInputTap($event)"></el-input>
                        <span v-else>{{ scope.row.hehao }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="qi" label="起" width="180" align="center">
                    <template slot-scope="scope">
                        <div v-if="!isdisabled">
                            <el-input type="number" v-model="scope.row.qi" placeholder="请输入"
                            @change.native="changeInputTap($event, scope.row, scope.$index, 0)"
                            :disabled="scope.row.qi != '' && scope.$index == 0"></el-input>
                        </div>
                        <div v-else>
                            <el-input type="number" v-model="scope.row.qi" placeholder="请输入"
                            @change.native="changeInputTap($event, scope.row, scope.$index, 0)"
                           ></el-input>
                        </div>
                       

                    </template>
                </el-table-column>
                <el-table-column prop="zhi" label="止" align="center">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.zhi" placeholder="请输入"
                            @change.native="changeInputTap($event, scope.row, scope.$index1, 1)"
                            :disabled="scope.row.zhi != '' && tableData.length == scope.$index + 1"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="guige" label="规格" align="center" width="340px">
                    <template slot-scope="scope">
                        <!-- {{isAvailable.specId}}1====={{scope.row.specId}}==={{isAvailable.maxHehao}}{{scope.row.hehao}} -->
                        <el-select v-model="isAvailable.specId" placeholder="请选择" style="width:100%" disabled
                         v-if="scope.$index==0&&isAvailable.maxHehaoIsAvailable == 'yes'&&!isdisabled&&isAvailable.specId!=null">
                            <el-option v-for="itemx in scope.row.guige" :key="itemx.specId" :label="itemx.selectList"
                                :value="itemx.specId">
                            </el-option>
                        </el-select>
                        <el-select v-model="scope.row.specId" placeholder="请选择" style="width:100%" v-else-if="isAvailable.maxHehaoIsAvailable == 'yes'&&isAvailable.specId==null"
                            @change="onChangeSelectTap($event, scope.row)">
                            <el-option v-for="itemx in scope.row.guige" :key="itemx.specId" :label="itemx.selectList"
                                :value="itemx.specId">
                            </el-option>
                        </el-select>
                        <el-select v-model="scope.row.specId" placeholder="请选择" style="width:100%" v-else
                            @change="onChangeSelectTap($event, scope.row)">
                            <el-option v-for="itemx in scope.row.guige" :key="itemx.specId" :label="itemx.selectList"
                                :value="itemx.specId">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="danger"  icon="el-icon-delete"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="closeDelDialog">取消</el-button>
            <el-button type="primary" @click="submitTap">确定</el-button>
        </div>
    </el-dialog>
</template>
<script>
import "@/assets/styles/ruoyi.scss"
import { getMaxHehaoByCondition, saveBox } from "@/api/archive/filesManage/filesManageMenu.js"
import { getLastIndexOf } from "@/utils/index.js" //截取sub_table_name的
export default {
    props: ["open", "queryParams", 'ids', 'list', "boxType", "permitInfo", "categoryType"],
    watch: {
        boxType: {
            handler(valNew) {
                console.log(this.permitInfo,"--")
                if (valNew == 0) {
                    this.istypeText = '件号'
                } else {
                    this.istypeText = '案卷号'
                }


            },
            immediate: true
        }
    },
    data() {
        return {
            num: undefined,
            tableData: [],
            boxSpecList: [],
            type: "",
            isAvailable: "",
            istypeText: "",
            isdisabled:false

        }
    },
    created() {

    },

    methods: {
        //输入盒号
        onInputTap(val){
            var inputMax=this.isAvailable.maxHehao+1; //获取 盒号最大可输入数量
            var inputMax1=val;//获取当前输入盒号，给盒号连续改后续盒号

            //判断输入的数量不能大于盒号最大的盒号，也不能小于盒号最小的盒号
            if(val>inputMax||val<this.isAvailable.maxHehao){
                this.isdisabled=false
                
                this.$message({ message:"只能输入当前盒子和下一个盒子哦", type: 'warning' })
                //如果输入有误，则显示反正接口的当前连续上一个盒的盒号
                inputMax1=this.isAvailable.maxHehao; //接口返回的盒号复制给输入的盒号，给盒号连续改后续盒号修改
                //所有盒号追加
                for(var i in this.tableData){
                    this.tableData[i]['hehao']= inputMax1++ 
                }
           
               
            }else{
                //所有盒号追加
                for(var i in this.tableData){
                    this.tableData[i]['hehao']= inputMax1++ 
                }
                console.log(this.tableData,"00000000000000000")
            }
           
            if(  this.tableData[0]['hehao']==this.isAvailable.maxHehao){
                this.tableData[0]['qi']=this.isAvailable.start;
                this.isdisabled=false;
            }else{
                this.tableData[0]['qi']=""
               this.isdisabled=true;
            }
            
        },
        //关闭
        closeDelDialog() {
            this.$emit("closeDelDialog")
        },

        /**
         * 记录一段js:判断数组元素连续或者不连续
         *
         *  {如果我们拿到一个数组的解构是这样的：
            [‘2’,‘3’,‘5.5’,‘6’,‘7’,‘8’,‘12’,‘12.1’,‘13’,‘16’,‘17’]
            我们需要把它变成这样：
            2-3,5.5,6-8,12,12.1,13,16-17}
         */
        sort(arr) {
            var result = [];
            arr.forEach(function (v, i) {
                var temp = result[result.length - 1];
                if (!i) {
                    result.push([v]);
                } else if (v % 1 === 0 && v - temp[temp.length - 1] == 1) {
                    temp.push(v);
                } else {
                    result.push([v]);
                }
            });
            return result.map(function (v) {
                if (v.length == 1) {
                    return v;
                } else {

                    return v[0] + '-' + v[v.length - 1];
                }
            }).join(",");
        },

        //查询
        onQuery() {
            // console.log(this.permitInfo,"++++++++++++++++++++++++")
            this.tableData = [];
            var ids = this.ids.split(",")  //档案ID
            var ajhOrJh = this.permitInfo.ajhOrJhString.split(",") //件号或者卷号
            ajhOrJh.sort(function (a, b) { return a - b; })
            // console.log(ajhOrJh, this.sort(ajhOrJh))
            var sort = this.sort(ajhOrJh).split(",")//判断是否是连续数据
            var reg = /^[1-9]\d*$/

            if (this.num <= 0 || this.num == undefined || !reg.test(this.num)) {
                this.$message({ message: '请输入正整数', type: 'warning' });
                return false
            }
            if (this.num > ids.length) {
                this.$message({ message: ids.length + '个档案最多只能装' + ids.length + '个盒子哦', type: 'warning' })
                return false
            }

            if (this.num < sort.length) {
                this.$message({ message: '所选档案' + this.istypeText + '不连续，请至少选择' + sort.length + '个盒子哦', type: 'warning' })
                return false
            }

            this.isdisabled=false;


            getMaxHehaoByCondition({
                "categoryId": this.queryParams.categoryId,
                "daIdsStr": this.ids,
                "type": this.boxType
            }).then(res => {
                this.isAvailable = res.data;
                var maxHehao = res.data.maxHehao; //如果res.data.maxHehaoIsAvailable == 'yes'
                // res.data.boxSpecList.push({
                //     specName: 10,
                //     spectPage: 1,
                //     specCount: 500,
                //     specId: "11111"
                // })
                for (var i in res.data.boxSpecList) {
                    var dw = "mm";
                    if (res.data.boxSpecList[i].specDw == 0) {
                        dw = "mm";
                    } else if (res.data.boxSpecList[i].specDw == 1) {
                        dw = "cm";
                    }
                    // console.log(res.data.boxSpecList[i].specName+"mm(盒子页数"+res.data.boxSpecList[i].spectPage+"剩余盒子数"+res.data.boxSpecList[i].specCount+")")
                    res.data.boxSpecList[i].selectList = res.data.boxSpecList[i].specName + dw + "(盒子页数" + res.data.boxSpecList[i].spectPage + "剩余盒子数" + res.data.boxSpecList[i].specAcount + ")"
                }
                //如果maxHehaoIsAvailable==yes  //如果之前已装过盒子 例如：盒号是“1”  在装盒的话如果和上次的号连续件号或者卷号  会把当前的号装到之前的盒子里  maxHehao==1，之前的盒号
                if (res.data.maxHehaoIsAvailable == 'yes') {
                    if (this.num == 1) {
                        for (var i = 0; i < this.num; i++) {
                            this.tableData.push({
                                hehao: maxHehao,
                                qi: res.data.start,  //上次盒子里面的最后一个件号或者卷号
                                zhi: ajhOrJh.pop(), //当前的件号或者卷号
                                specId: res.data.boxSpecList[0].specId,//规格ID
                                guige: res.data.boxSpecList,  //规格
                            })
                        }

                    } else {
                        maxHehao = maxHehao - 1;
                        for (var i = 0; i < this.num; i++) {
                            if (i == 0) {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: res.data.start,  //上次盒子里面的最后一个件号或者卷号
                                    zhi: "", //当前的件号或者卷号
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                    guige: res.data.boxSpecList,  //规格

                                })
                            } else if (i == this.num - 1) {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: "",  //上次盒子里面的最后一个件号或者卷号
                                    zhi: ajhOrJh.pop(), //当前的件号或者卷号
                                    number: res.data.start,
                                    guige: res.data.boxSpecList,  //规格
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                })
                            } else {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: "",  //上次盒子里面的最后一个件号或者卷号
                                    zhi: "", //当前的件号或者卷号
                                    number: res.data.start,
                                    guige: res.data.boxSpecList,  //规格
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                })
                            }

                        }
                    }

                    console.log(this.tableData,"++++++++++++++++")

                }

                //如果maxHehaoIsAvailable==no  不连续装盒，新建个盒子
                if (res.data.maxHehaoIsAvailable == 'no') {
                    for (var i = 0; i < this.num; i++) {

                        if (this.num == 1) {
                            for (var i = 0; i < this.num; i++) {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: ajhOrJh[0],  //起始
                                    zhi: ajhOrJh.pop(), //截止
                                    guige: res.data.boxSpecList,  //规格
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                })
                            }
                        } else {
                            if (i == 0) {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: ajhOrJh[0],  //起始
                                    zhi: "", //截止
                                    number: ajhOrJh[0],
                                    guige: res.data.boxSpecList,  //规格
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                })
                            } else if (i == this.num - 1) {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: "",  //起始
                                    zhi: ajhOrJh.pop(), //截止
                                    //number:sort[i],
                                    guige: res.data.boxSpecList,  //规格
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                })
                            } else {
                                this.tableData.push({
                                    hehao: maxHehao += 1,
                                    qi: "",  //起始
                                    zhi: "", //截止
                                    number: ajhOrJh[0],
                                    specId: res.data.boxSpecList[0].specId,//规格ID
                                    guige: res.data.boxSpecList,  //规格
                                })
                            }
                        }

                    }
                }

                console.log(this.tableData, "11111111111")
            })




        },

        // //输入input  进行判断是否是可选的件号或者是卷号
        changeInputTap(e, row, index, text) {
            console.log(row,"klsdjfkl--")
            var ajhOrJhStr = this.permitInfo.ajhOrJhString.split(",") //件号或者卷号
           var ajhOrJh= ajhOrJhStr.sort(function (a, b) { return a - b; }) //排序
           
            var isif = ajhOrJh.filter(item => { return item == e.target.value })
           console.log(ajhOrJh, isif, row, this.isAvailable)

            if (isif.length <= 0) {
                this.$alert('填写的' + this.istypeText + '必须等于勾选的档案的件号的其中一个', '', {
                    confirmButtonText: '确定',
                    type: 'warning',
                    callback: action => {
                        console.log(e, row, index, text)
                        if (text == "0") {
                            for (var i in this.tableData) {
                                if (this.tableData[i].hehao == row.hehao) {
                                    this.tableData[i].qi = "";
                                }
                            }
                        }
                        if (text == "1") {
                            for (var i in this.tableData) {
                                if (this.tableData[i].hehao == row.hehao) {
                                    this.tableData[i].zhi = "";
                                }
                            }
                        }

                    }
                });

                return false

            } else {

                var data = []
                // console.log(row.qi, row.zhi,this.isAvailable,"liuhaiorng")
              
            //    1、如果之前装过盒 连续  yes    2、选的档案用一个新盒子  yes     3 如果之前装过盒 不连续  no 
                if (this.isAvailable.maxHehaoIsAvailable=='yes'&&this.isAvailable.boxEndNum!=undefined ) {
                    var qi = parseInt(this.isAvailable.boxEndNum) + 1
                    data = this.jsonStartOrEnd(ajhOrJh, qi, row.zhi)
                }else {
                    data = this.jsonStartOrEnd(ajhOrJh, row.qi, row.zhi)
                }

                console.log(data,"++++++++++++++++")
                if (!this.isContinuityNum(data)) {
                  
                    this.$alert('填写的' + this.istypeText + '不连续哦', '', {
                        confirmButtonText: '确定',
                        type: 'warning',
                        callback: action => {
                            console.log(e, row, index, text)
                            if (text == "0") {
                                for (var i in this.tableData) {
                                    if (this.tableData[i].hehao == row.hehao) {
                                        this.tableData[i].qi = "";
                                    }
                                }
                            }
                            if (text == "1") {
                                for (var i in this.tableData) {
                                    if (this.tableData[i].hehao == row.hehao) {
                                        this.tableData[i].zhi = "";
                                    }
                                }
                            }

                        }
                    });

                    return false
                }

            }




        },

        //选择列表规格
        onChangeSelectTap(e, row) {
            console.log(e, row, "ksdfjkl")
        },
        //删除
        handleDelete(row) {
            var that=this;
            var ajhOrJh = this.permitInfo.ajhOrJhString.split(",") //件号或者卷号
            ajhOrJh.sort(function (a, b) { return a - b; }) //排序
            var sort = this.sort(ajhOrJh).split(",")//判断是否是连续数据
            // console.log(this.tableData,sort,row,"------------测试数据")

            if (this.tableData.length <= sort.length) {
                this.$message({ message: '当前盒的数量为需要的盒的最小数量，不允许删除', type: 'warning' })
                return false
            }
            var list=[];
            for (var i in this.tableData) {
                //  console.log(this.tableData[i].hehao != row.hehao,"sdlfjsdklj")
                 if(this.tableData[i].hehao != row.hehao){
                    list.push({
                        guige:this.tableData[i].guige,
                        hehao:this.tableData[0].hehao++,
                        number:this.tableData[i].number,
                        qi:this.tableData[i].qi,
                        specId:this.tableData[i].specId,
                        zhi:this.tableData[i].zhi

                    })
                   
                 }
            }
         list[list.length - 1].zhi=this.tableData[this.tableData.length - 1].zhi
         list[0].qi = this.tableData[0].qi;
            this.tableData=list

        },

        //确定装盒
        submitTap() {
            for (var i in this.tableData) {
                if (this.tableData[i].zhi == "" || this.tableData[i].qi == "") {
                    this.$message({ message: '请输入盒号是' + this.tableData[i].hehao + "的起止" + this.istypeText + "哦", type: 'warning' })
                    return false
                }

                //  console.log(this.tableData[i].zhi < this.tableData[i].qi,typeof(this.tableData[i].zhi ),typeof(this.tableData[i].qi ),":止件号："+this.tableData[i].zhi, "启件号："+this.tableData[i].qi)
                if (parseInt(this.tableData[i].zhi) < parseInt(this.tableData[i].qi)) {
                    console.log(this.tableData[i].zhi < this.tableData[i].qi, ":止" + this.istypeText + "：" + this.tableData[i].zhi, "启件号：" + this.tableData[i].qi)
                    this.$message({ message: '盒号为' + this.tableData[i].hehao + "止" + this.istypeText + "不能小于起" + this.istypeText, type: 'warning' })
                    return false
                }
                //console.log(i, this.tableData.length)
                if (i != this.tableData.length - 1) {
                    if (this.tableData[i].zhi == this.tableData[parseInt(i) + 1].qi) {
                        this.$message({ message: '盒号为' + this.tableData[i].hehao + '的盒中还有其他件，因此' + this.istypeText + '为' + this.tableData[i].zhi + ' 的档案不允许拆开分装到两个盒中', type: 'warning' })
                        return false

                    }
                }
             
                if (i != this.tableData.length - 1) {
                    console.log(parseInt(this.tableData[i].zhi), this.tableData[parseInt(i) + 1].qi,this.tableData[parseInt(i) + 1],this.tableData[i])
                    if (parseInt(this.tableData[i].zhi) >= parseInt(this.tableData[parseInt(i) + 1].qi)) {
                        this.$message({ message: '第'+this.tableData[i].hehao+'行的止' + this.istypeText + '不能大于第'+this.tableData[parseInt(i) + 1].hehao+'行的起' + this.istypeText, type: 'warning' })
                        return false
                    }
                }
            }
            var ajhOrJh = this.permitInfo.ajhOrJhString.split(",") //件号或者卷号

         
            var ids = this.permitInfo.ids.split(",") //件ID或者卷ID
            
             //获取打算装盒的件号
             var listStr = [];
            for (var i in ajhOrJh) {
                listStr.push({
                    JH:ajhOrJh[i],
                    id: ids[i]
                })
            }
          //  console.log(this.tableData,"this.tableData")
          //  console.log(ajhOrJh,ids,listStr,"88888888888888",this.isAvailable)
            //1、如果之前装过盒 连续  yes    2、选的档案用一个新盒子  yes     3 如果之前装过盒 不连续  no 
            //获取已准备装盒的件号
            var pushStr=[]
            for(var t in this.tableData){
                var data=[]
               
                if (this.isAvailable.maxHehaoIsAvailable=='yes'&&this.isAvailable.boxEndNum!=undefined) {
                    var qi =""
                    if(this.tableData[t].qi==this.isAvailable.boxEndNum){
                        qi = parseInt(this.isAvailable.boxEndNum) + 1
                    }else{
                        qi=this.tableData[t].qi
                    }
                    //ajhOrJh.unshift(this.isAvailable.boxEndNum); // 在数组开头添加元素 this.isAvailable.boxEndNum
                    data= this.jsonStartOrEnd(ajhOrJh,qi,this.tableData[t].zhi);
                //    console.log(data,"===============1")
                }else{
                 // console.log(ajhOrJh,this.tableData[t].qi+'',this.tableData[t].zhi)
                    data=this.jsonStartOrEnd(ajhOrJh,this.tableData[t].qi+'',this.tableData[t].zhi);
                   // console.log(data,"===============2")
                }
                //console.log(ajhOrJh,this.tableData[t].qi,this.tableData[t].zhi,data,"++++++++++++++++++data++++++++++++++++++++++")
               // console.log(this.isAvailable,this.tableData[t].hehao,this.tableData[t].hehao==1&&this.isAvailable.maxHehaoIsAvailable=='yes'&&this.isAvailable.boxEndNum!=undefined,data,"+++++++++++++++++++++++++++++++++++")
                
                pushStr=pushStr.concat(data)
            }

            var list=[];//获取已准备装的件号的ID 和档案id
            var listIds=[];//获取已准备装的件号的ID
           // console.log(pushStr,"++++++++++++")
            for(var i in pushStr){
                for(var j in listStr){
                    if(pushStr[i]==listStr[j].JH){
                        list.push({
                            JH: pushStr[i],
                            id:  listStr[j].id
                           
                        })
                        listIds.push(listStr[j].id)
                    }
                }
            }
            console.log(list,"++++")
            
            //以下是组装heData参数的
            var heData = [];
            for (var k in this.tableData) {
                var narr = [];
                for (var i = 0; i < ajhOrJh.length; i++) {
                    if (ajhOrJh[i] >= parseInt(this.tableData[k].qi) && ajhOrJh[i] <= parseInt(this.tableData[k].zhi)) {
                        narr.push(ajhOrJh[i]);
                    }
                }
                var ddd = []
                for (var w in list) {
                    for (var n in narr) {
                        if (narr[n] == list[w].JH) {
                            ddd.push(list[w].id);
                        }
                    }
                }
               
                heData.push({
                    daIds: ddd.toString(),
                    hehao: this.tableData[k].hehao,
                    box_stnum: this.tableData[k].qi,
                    box_ednum: this.tableData[k].zhi,
                    spec_id: this.tableData[k].specId
                })
            }         
            if (heData.length == 0) {
                this.$message({ message: '没有要保存的数据', type: 'warning' })
                return false
            } else {
                saveBox({
                    categoryId: this.queryParams.categoryId,
                    heData: heData,
                    daIdsStr: listIds.toString(),
                    type: this.categoryType,
                }).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        this.$modal.msgSuccess("装盒成功");
                        this.$emit("submitTap")
                    }
                })
            }

        }
    }
}
</script>
<style scoped>
::v-deep .el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: calc(100% - 30px);
    max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding: 10px 20px 10px !important;
}

.boxMain {
    height: 400px;
}
</style>
